package com.aster.common.api.service.imp;

import com.aster.common.api.dao.SmsCheckDao;
import com.aster.common.api.domain.TbSmsCheck;
import com.aster.common.api.service.SmsCheckService;
import com.aster.common.api.service.criteria.SmsCheckCriteria;
import com.aster.common.base.BaseServiceImpl;
import com.aster.common.exception.ServiceException;
import com.aster.common.utils.DateUtil;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 
 * <br>
 * <b>功能：</b>TbSmsCheckService<br>
 */
@Service("smsCheckService")
public class  SmsCheckServiceImpl  extends BaseServiceImpl implements SmsCheckService {
  private final static Logger log= Logger.getLogger(SmsCheckServiceImpl.class);
	

	@Autowired
    private SmsCheckDao dao;

		
	public SmsCheckDao getDao() {
		return dao;
	}


	@Override
	public void sendSmsCode(String tel) throws ServiceException {
		try {
			TbSmsCheck tbSmsCheck = getSmsCheck("tel",tel);
			Date expirTime = new Date();
			Date now = new Date();
			expirTime.setTime(now.getTime()+60*60*1000);
			if(tbSmsCheck == null){
				tbSmsCheck = new TbSmsCheck();
				tbSmsCheck.setTel(tel);
				tbSmsCheck.setVerificationCode("123");
				tbSmsCheck.setExpirTime(expirTime);
				tbSmsCheck.setUpdateTime(now);
				super.add(tbSmsCheck);
			}
			TbSmsCheck updateSmsCheck = new TbSmsCheck();
			updateSmsCheck.setId(tbSmsCheck.getId());
			updateSmsCheck.setVerificationCode("123");
			updateSmsCheck.setUpdateTime(now);
			updateSmsCheck.setExpirTime(expirTime);
			super.updateBySelective(updateSmsCheck);
		}catch (Exception ex){
			throw new ServiceException(55555,ex.getMessage());
		}
	}

	@Override
	public void generalUserLoginCodeCheck(String tel, String code) throws ServiceException {
		TbSmsCheck tbSmsCheck = getSmsCheck("tel",tel);
		if(null == tbSmsCheck){
			throw new ServiceException(20004,"用户登录验证码不存在，请重新获取");
		}
		if(tbSmsCheck.getExpirTime().getTime()< DateUtil.nowDateTIme().getTime()){
			throw new ServiceException(20005,"验证码已经过期，请重新获取");
		}
		if(!code.equals(tbSmsCheck.getVerificationCode())){
			throw new ServiceException(20005,"验证码错误");
		}
	}

	private TbSmsCheck getSmsCheck(String key,Object value) throws ServiceException {
		try {
			SmsCheckCriteria smsCheckCriteria = new SmsCheckCriteria();
			smsCheckCriteria.put(key,value);
			TbSmsCheck tbSmsCheck = dao.getSmsCheck(smsCheckCriteria);
			return tbSmsCheck;
		}catch (Exception ex){
			throw new ServiceException(55555,ex.getMessage());
		}

	}
}
